import { getToken } from '@/utils/auth' // get token from cookie
/* Layout */
import Layout from '@/layout'
import $ from 'jquery'
import component from './page'

export function getRouter() {
  var asyncRouters = []

  if (getToken()) {
    $.ajax({
      url: process.env.VUE_APP_BASE_API + '/user/menu',
      async: false,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      success: function(res) {
        var index = 0
        for (const item in res.data.menus) {
          ++index
          const data = res.data.menus[item]
          const menuItem = {}
          menuItem.meta = { title: data.title }
          menuItem.component = Layout
          menuItem.alwaysShow = true
          menuItem.path = 'menu' + index

          if (data.children.length > 0) {
            menuItem.redirect = data.children[0].url
            menuItem.children = []
            for (const key in data.children) {
              const childData = data.children[key]
              const childNode = {}
              childNode.path = childData.url
              childNode.meta = { title: childData.title }
              if (component[childData.url] !== undefined) {
                childNode.hidden = component[childData.url]['hidden']
                childNode.component = () => component[childData.url]['page']
              }
              menuItem.children.push(childNode)
            }
          } else {
            menuItem.hidden = true
          }
          asyncRouters.push(menuItem)
        }
      }
    })
  }

  return asyncRouters
}
